package negocio
import java.util.Date
import negocio.InscricaoService

class EventoController extends BaseSecureController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST",participar:"POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [eventoInstanceList: Evento.list(params), eventoInstanceTotal: Evento.count()]
    }
    //procura por usuario
    def listMeus={
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        def eventos=Evento.findAllByDono(this.&getUserLogged(),params)
        [eventoInstanceList:eventos,eventoInstanceTotal:Evento.count()]
    }
    def listeEstouInscritos={
        def eventoInscrito=EventoTemInscrito.findAllByUsuario(getUserLogged())
        return [eventoListaEstouInscritos:eventoInscrito]
    }

    def listeUltimos={
         def valor=params.limite?params.limite:2
         def eventoUltimos=EventoTemInscrito.findAllByUsuario(this.&getUserLogged(),
                                       [max:valor, offset:0,sort:"data",order:"desc"])
        //eventoInscrito?.each{println it}
        return [ultimosEventos:eventoUltimos]
    }
    def listeUltimosParticipei={
        def valor=params.limite?params.limite:5
        Date data= new Date()
        def sql="FROM EventoTemInscrito ins WHERE ins.evento.fim<:dataFim AND "
            sql=+" ins.usuario=:user"
        def eventoUltimos=EventoTemInscrito.findAll(sql,
                                       [max:valor, offset:0,sort:"data",order:"asc",dataFim:data,user:this.&getUserLogged()])
        //eventoInscrito?.each{println it}
        return [ultimosEventos:eventoUltimos]
    }

    def listeProximosPaticiparei={
        def valor=params.limite?params.limite:5
        Date data= new Date()
        def sql="FROM EventoTemInscrito ins WHERE ins.evento.inicio>:dataInicio AND "
            sql=+" ins.usuario=:user"
        def proximosEventos=EventoTemInscrito.findAll(sql,
                                       [max:valor, offset:0,sort:"data",order:"asc",dataInicio:data,user:this.&getUserLogged()])
        //eventoInscrito?.each{println it}
        return [proximosEventos:proximosEventos]

    }

    def listeAndamento={
        def user=getUserLogged()
        Date data= new Date()
        def sql="FROM EventoTemInscrito ins WHERE ins.evento.inicio<=:dataInicio AND "
            sql+="ins.evento.fim>=:dataFim AND ins.usuario=:user"
        //def eventoLista=Evento.findAllByInicioLessThanEqualsAndFimGreaterThanEquals(data,data)
        def eventoLista=EventoTemInscrito.findAll(sql,[dataInicio:data,dataFim:data,user:user])
        return [eventoListaEstouInscritos:eventoLista]
    }

    def create = {
        def eventoInstance = new Evento()
        eventoInstance.properties = params
        return [eventoInstance: eventoInstance]
    }

    def save = {
        def eventoInstance = new Evento(params)
        eventoInstance.setDono(this.&getUserLogged())
        if (eventoInstance.save(flush: true)) {
           /* params.each{println it}
            println 'valores do objeto'
            eventoInstance.properties.each{println it}*/
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'evento.label', default: 'Evento'), eventoInstance.nome])}"
            redirect(action: "show", id: eventoInstance.id)
        }
        else {
            render(view: "create", model: [eventoInstance: eventoInstance])
        }
    }

    def show = {
        def eventoInstance = Evento.get(params.id)
        if (!eventoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'evento.label', default: 'Evento'), params.id])}"
            redirect(action: "list")
        }
        else {
            [eventoInstance: eventoInstance]
        }
    }

    def edit = {
        def eventoInstance = Evento.get(params.id)
        if (!eventoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'evento.label', default: 'Evento'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [eventoInstance: eventoInstance]
        }
    }

    def update = {
        def eventoInstance = Evento.get(params.id)
        if (eventoInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (eventoInstance.version > version) {

                    eventoInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'evento.label', default: 'Evento')] as Object[], "Another user has updated this Evento while you were editing")
                    render(view: "edit", model: [eventoInstance: eventoInstance])
                    return
                }
            }
            eventoInstance.properties = params
            if (!eventoInstance.hasErrors() && eventoInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'evento.label', default: 'Evento'), eventoInstance.nome])}"
                redirect(action: "show", id: eventoInstance.id)
            }
            else {
                render(view: "edit", model: [eventoInstance: eventoInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'evento.label', default: 'Evento'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def eventoInstance = Evento.get(params.id)
        if (eventoInstance) {
            try {
                eventoInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'evento.label', default: 'Evento'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'evento.label', default: 'Evento'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'evento.label', default: 'Evento'), params.id])}"
            redirect(action: "list")
        }
    }

}
